import 'dart:ui';

import 'package:flutter/material.dart';
import 'touch_info.dart';

class Beziier2Painter extends CustomPainter {
  Paint _helpPaint = Paint()
    ..color = Colors.purple
    ..style = PaintingStyle.stroke
    ..strokeCap = StrokeCap.round;

  final TouchInfo repaint;

  Beziier2Painter({required this.repaint}) : super(repaint: repaint);
  List<Offset> pos = [];
  Path _path = Path();
  Paint _mainPaint = Paint()
    ..color = Colors.orange
    ..style = PaintingStyle.stroke
    ..strokeWidth = 2;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.translate(size.width / 2, size.height / 2);

    pos = repaint.points
        .map((e) => e.translate(-size.width / 2, -size.height / 2))
        .toList();

    _path.reset();
    if (pos.length < 3) {
      canvas.drawPoints(PointMode.points, pos, _helpPaint..strokeWidth = 8);
    } else {
      _path.moveTo(pos[0].dx, pos[0].dy);
      _path.quadraticBezierTo(pos[1].dx, pos[1].dy, pos[2].dx, pos[2].dy);
      canvas.drawPath(_path, _mainPaint);
      _drawHelp(canvas);
      _drawSelectPos(canvas, size);
    }
  }

  void _drawHelp(Canvas canvas) {
    _helpPaint..color = Colors.purple;
    canvas.drawPoints(PointMode.polygon, pos, _helpPaint..strokeWidth = 1);
    canvas.drawPoints(PointMode.points, pos, _helpPaint..strokeWidth = 8);
  }

  void _drawSelectPos(Canvas canvas, Size size) {
    Offset? selectPos = repaint.selectPoint;
    if (selectPos == null) return;
    selectPos = selectPos.translate(-size.width / 2, -size.height / 2);
    canvas.drawCircle(
        selectPos,
        10,
        _helpPaint
          ..color = Colors.green
          ..strokeWidth = 2);
  }

  @override
  bool shouldRepaint(Beziier2Painter oldDelegate) =>
      oldDelegate.repaint != repaint;
}
